package station;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class UDPWorker implements Runnable {

	private volatile boolean running;
	private final int UDPPORT;
	private SenderThread st;
	private DatagramSocket ds;
	private DatagramPacket dp;
	private byte[] rcvdData = new byte[24];		//Array, in das die Daten der DataSource �bertragen werden
	private int rcv_timeout = 1500;
	private boolean socketClosed = false;
	
	public UDPWorker(SenderThread st, int port){
		this.running = true;
		this.st = st;
		this.UDPPORT = port;
	
		try {				//UDP Socket initialisieren
			ds = new DatagramSocket(UDPPORT);
			ds.setSoTimeout(rcv_timeout);
			dp = new DatagramPacket(rcvdData, rcvdData.length);	
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	
	public void run() {
		while(running){
			try {
				if(!socketClosed){
					ds.receive(dp);
				}else{
					ds.close();
				}
			} catch (SocketTimeoutException ste){
				//System.out.println("Receive timed out.");
			} catch (IOException e) {
				e.printStackTrace();
			}
//			String testAusgabe = new String(rcvdData);
//			System.out.println("UDPWorker: " + testAusgabe);
			st.setContent(rcvdData);	
		}
	}//run
	
	public void terminate(){
		this.socketClosed = true;
		this.running = false;
		System.out.println("UDPWorker...");
	}
}
